package com.cdu.guoxinan.www.smartcom.config;

import com.cdu.guoxinan.www.smartcom.util.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers()
                .frameOptions().sameOrigin() // 允许同源iframe嵌套
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 公开接口，无需认证
                .antMatchers(
                        "/user/login", "/user/register", "/user/sendCode", "/user/reset-password","/user/queryByEmail",
                        "/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs","/user/queryByUsername",
                        "/index.html", "/login.html","/register.html", "/css/**", "/js/**", "/lib/**", "/images/**", "/api/**", "/page/*.html", "/**/*.js", "/**/*.css", "/**/*.png", "/**/*.jpg", "/**/*.ico"
                ).permitAll()
                // 超级管理员专用接口
                .antMatchers("/page/**","/role/**","/syslog/**").hasRole("SUPERADMIN")
                // 管理员和超级管理员可以访问的接口
                .antMatchers("/user/add", "/user/update", "/user/delete", "/repairMan/**","/fee/**").hasAnyRole("ADMIN", "SUPERADMIN")
                // 普通用户、管理员、超级管理员都可以访问的接口
                .antMatchers("/user/query", "/userFee/**").hasAnyRole("USER", "ADMIN", "SUPERADMIN")
                // 其他所有请求需要认证
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}